package com.elitesland.b2c.tms.repo;

import com.elitesland.b2c.tms.entity.QTmsFareTmplDO;
import com.elitesland.core.constant.CommonConstant;
import com.querydsl.core.types.ExpressionUtils;
import com.querydsl.core.types.Predicate;
import com.querydsl.jpa.impl.JPAQueryFactory;
import lombok.NonNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * <p>
 * 功能说明
 * </p>
 *
 * @author fred
 * @since 2021-02-03 19:16:12
 */
@Repository
public class TmsFareTmplRepoProc {

    @Autowired
    private JPAQueryFactory jpaQueryFactory;

    private final QTmsFareTmplDO qTmsFareTmplDO = QTmsFareTmplDO.tmsFareTmplDO;

    /**
     * 更新是否启用
     *
     * @param ids    模板ID
     * @param enable 是否启用
     */
    public void updateEnable(List<Long> ids, Boolean enable) {
        jpaQueryFactory.update(qTmsFareTmplDO)
                .set(qTmsFareTmplDO.enabled, enable)
                .where(qTmsFareTmplDO.id.in(ids))
                .execute();
    }

    /**
     * 删除模板信息
     *
     * @param ids 模板ID
     */
    public void delete(List<Long> ids) {
        jpaQueryFactory.update(qTmsFareTmplDO)
                .set(qTmsFareTmplDO.deleteFlag, CommonConstant.COMMON_DELETE_YES)
                .where(qTmsFareTmplDO.id.in(ids))
                .execute();
    }

    /**
     * 判断名称是否存在
     *
     * @param name 模板名称
     * @param id   模板ID
     * @return 是否存在
     */
    public boolean existsName(@NonNull String name, Long id) {
        Predicate predicate = qTmsFareTmplDO.name.eq(name);
        if (id != null) {
            predicate = ExpressionUtils.and(predicate, qTmsFareTmplDO.id.ne(id));
        }
        predicate = ExpressionUtils.and(predicate, qTmsFareTmplDO.deleteFlag.eq(CommonConstant.COMMON_DELETE_NO));

        return jpaQueryFactory.select(qTmsFareTmplDO.id)
                .from(qTmsFareTmplDO)
                .where(predicate)
                .limit(1)
                .fetchOne() != null;
    }

    /**
     * 获取名称
     *
     * @param id 模板ID
     * @return 模板名称
     */
    public String getName(Long id) {
        return jpaQueryFactory.select(qTmsFareTmplDO.name)
                .from(qTmsFareTmplDO)
                .where(qTmsFareTmplDO.id.eq(id))
                .fetchOne();
    }

    /**
     * 获取启用状态
     *
     * @param id 模板ID
     * @return 是否启用
     */
    public Boolean getEnable(Long id) {
        return jpaQueryFactory.select(qTmsFareTmplDO.enabled)
                .from(qTmsFareTmplDO)
                .where(qTmsFareTmplDO.id.eq(id))
                .fetchOne();
    }
}